import { pos, simplePos, simplePosObj } from "../anim/PosDefine";
import UIConfig from "../config/UIConfig";
import PoolObj from "../pool/PoolObj";
import SoundHelp from "../sound/SoundHelp";
import TimeManage from "../time/TimerManage";
import ObjectUtils from "./ObjectUtils";
import Tween from "../anim/Tween";
import Utils from "./Utils";


export default class UIUtils {

    static getCell<T>(list: Laya.List, index: number): T {
        return list.getCell(index) as unknown as T;
    }

    /**
     * 舞台转本地,默认锚点为中心点
     */
    static globalToLocal(sprite: Laya.Sprite, x?: number, y?: number): simplePos {
        const temp = Laya.Point.TEMP;
        !Utils.isNil(x) && (x = sprite.width >> 1)
        !Utils.isNil(x) && (y = sprite.height >> 1)
        temp.setTo(x, y);
        sprite.globalToLocal(temp);
        return [temp.x, temp.y];
    }

    /**
     * 子控件水平居中，忽略隐藏节点
     * @param parent 当前节点
     * @param dist 子控件的间隔
     */
    static centerChild(parent: Laya.Sprite, num?: number, dist: number = 0): void {
        let len = parent.numChildren;
        if (len > 0) {
            let sum = 0, i, j = 0, arr = [];
            num === void 0 && (num = len);
            for (i = 0; i < len; i++) {
                let csi = parent.getChildAt(i) as Laya.Sprite;
                if (!csi.visible) continue;
                sum += csi.width;
                arr.push(csi);
                if (++j >= num) {
                    break;
                }
            }

            len = arr.length;
            // 起点横坐标
            sum = (parent.width - sum - (len - 1) * dist) / 2;
            for (i = 0; i < len; i++) {
                arr[i].x = sum;
                sum += arr[i].width + dist;
            }
        }
    }

    /**
     * 初始化视频分享按钮，自带总开关控制
     * @param btn 按钮
     * @param module 模块
     * @param childIdx 子控件下标，默认修改按钮本身，若大于-1，则修改子控件图片，若小于0，则不修改
     * @param format 采用“%s”来代替“video”或“share”的命名格式，默认'game/img_%s_icon.png'
     * @returns 配置，大于0为正常，1为分享，2为视频，总开关关闭时也返回0
     */
    public static initVSBtn(btn: Laya.Sprite, module: string, childIdx?: number, format?: string): number {
        let bool = false, config = 0;
        if (module) {
            // let isOpen = GameConst.canShare();
            // config = isOpen ? StrategyMgr.getStrategyByModule(module) : 2;  // 默认策略，因游戏而定，一般是未有流量主是0，有流量主后2
            // config = 2;     // 仅视频

            //TODO

            bool = config > 0;
            if (bool && !(childIdx < 0)) {
                let child = <Laya.Sprite>(childIdx > -1 && btn.getChildAt(childIdx) || btn);
                let skin = ObjectUtils.formatString((format || 'main/icon_%s.png'), (config == 2 ? 'video' : 'share'));
                if (child instanceof Laya.Image)
                    child.skin = skin;
                else {
                    child.loadImage(skin)
                }
                child.visible = true;
            }
        }
        if (!bool) {
            let child = btn.getChildAt(childIdx) as Laya.Sprite;
            if (child) {
                child.visible = false;
                UIUtils.centerChild(btn, 1);
            }
        }
        return config;
    }


    /**
     * 添加点击事件
     * @param node 点击对象
     * @param func 回调
     * @param thisObj 回调对象
     * @param once 仅监听一次
     * @param data 回调参数
     * @param time 多次点击阻断，默认0
     * 注：事件清理请使用offAll
     */
    public static addClick(node: Laya.Sprite, func: Function, thisObj?: any, data?: any[], once: boolean = false, time: number = 0, sound: string = null): void {
        let fun = once ? "once" : "on", clickTime = 0, params = [];
        // 防止多次监听  list时可能会出现多次监听
        node.offAll(Laya.Event.CLICK);
        // 当需要传参时，修改回调参数
        if (data != null) {
            params.push(...data);
            // evtIdx = 1;
        }
        node[fun](Laya.Event.CLICK, thisObj, function (e: Laya.Event) {
            const now = TimeManage.I.ms;
            e.stopPropagation();
            if (now - clickTime < time) {
                // UIMgr.showTips("您的操作过快，请稍后操作");
                return;
            }
            params.push(e);
            sound && SoundHelp.Instance().playSound(sound);
            func && func.apply(thisObj, params);
            clickTime = now;
        });

        const oldsx = node.scaleX, oldsy = node.scaleY;
        this.setPivot(node);

        // 点击动画
        let isTouch = false;
        const nextx = oldsx + (oldsx > 0 ? 1 : -1) * 0.1;
        const nexty = oldsy + (oldsy > 0 ? 1 : -1) * 0.1;
        const tOnce = Tween.once;

        node.on(Laya.Event.MOUSE_DOWN, thisObj, onDown);
        node.on(Laya.Event.MOUSE_UP, thisObj, onOut);
        node.on(Laya.Event.MOUSE_OUT, thisObj, onOut);

        function onDown(e: Laya.Event) {
            isTouch = true;
            e.stopPropagation();
            tOnce(node).to({ scaleX: nextx, scaleY: nexty }, 100);
        }

        function onOut(e: Laya.Event) {
            if (isTouch) {
                isTouch = false;
                e.stopPropagation();
                tOnce(node).to({ scaleX: oldsx, scaleY: oldsy }, 100);
            }
        }
    }

    /**
     * 设置锚点居中
     * @param node 
     */
    public static setPivot(node: Laya.Sprite) {

        const oldsx = node.scaleX, oldsy = node.scaleY;
        if (node instanceof Laya.UIComponent) {
            if (isNaN(node.anchorX)) {
                node.anchorX = 0.5;
                node.x += node.width * 0.5 * oldsx;
            }
            if (isNaN(node.anchorY)) {
                node.anchorY = 0.5;
                node.y += node.height * 0.5 * oldsy;
            }
        }
        else if (node instanceof Laya.Sprite) {
            if (node.pivotX === 0) {
                node.pivotX = node.width * 0.5 * oldsx;
                node.x += node.width * 0.5 * oldsx;
            }
            if (node.pivotY === 0) {
                node.pivotY = node.height * 0.5 * oldsy;
                node.y += node.height * 0.5 * oldsy;
            }
        }
    }


    public static setBadge(sp: Laya.Sprite, active: boolean, skin?: string, pos?: simplePosObj, pivot?: simplePos) {
        let badge = sp.getChildByName(badgeItem.key) as badgeItem;
        pos = Utils.isNil(pos) ? Object.create(null) : pos;

        if (!active) {
            badge && badge.setActive(false, UIConfig.badgeRecover);
            return;
        }

        if (Utils.isNil(badge)) {
            badge = badgeItem.create(skin, pivot);
            badge.initPos(sp, pos.x, pos.y);
        }

        badge.setActive(true);

    }


    /**
     * 绘制相机渲染到Sprite
     * @param camera 
     * @param sp 
     */
    public static drawTexture(camera: Laya.Camera, sp: Laya.Sprite) {
        let renderTarget = camera.renderTarget;
        let rederTex = new Laya.Texture(<Laya.Texture2D>(renderTarget as any), Laya.Texture.DEF_UV);
        sp.graphics.drawTexture(rederTex);
    }

    /**
     * 添加click监听
     */
    public static addClick2(target: Laya.Sprite, call: Function, thisObj?: any): void {
        target.on(Laya.Event.CLICK, thisObj, call);
    }

}

class badgeItem extends Laya.Sprite {

    static key = "_badgeitem_";

    static create(skin?: string, pivot?: simplePos) {
        let elm = <badgeItem>PoolObj.getItemByClass(this.key, badgeItem);
        elm.name = this.key;
        elm.init(skin, pivot);
        return elm;
    }

    static recover(item: badgeItem) {
        item.removeSelf();
        PoolObj.recover(this.key, item);
    }


    //============================================

    private $tween: Laya.TimeLine;
    private $skin: string;


    private init(skin?: string, pivot?: simplePos) {
        skin == null && (skin = "images/common/red_point_big.png");
        if (Laya.loader.getRes(skin)) {
            this.loadImage(skin);
            pivot = pivot == null ? [this.width >> 1, this.height] : pivot;
            this.pivotX = pivot[0];
            this.pivotY = pivot[1];
        } else {
            Laya.loader.load(skin, Laya.Handler.create(this, () => {
                this.loadImage(skin);
                pivot = pivot == null ? [this.width >> 1, this.height] : pivot;
                this.pivotX = pivot[0];
                this.pivotY = pivot[1];
            }))
        }
    }

    private getEff(create: boolean) {

        if (!Utils.isNil(this.$tween)) {
            return this.$tween;
        }

        if (create) {
            let pos = [this.x, this.y]
            this.$tween = Laya.TimeLine.to(this, { scaleX: 1.3, scaleY: 0.3 }, 200, null, 500)
                .to(this, { scaleX: 0.8, scaleY: 1.3, y: pos[1] - 30 }, 300)
                .to(this, { scaleX: 1.3, scaleY: 0.3, y: pos[1] }, 300)
                .to(this, { scaleX: 1, scaleY: 1 }, 200)

            this.$tween.play(null, true);
        }

        return this.$tween;
    }

    setIcon(skin: string, complete: Laya.Handler) {
        if (this.$skin === skin) return;

        this.$skin = skin;
        this.loadImage(skin, complete)
    }


    //默认右上角
    initPos(parent: Laya.Sprite, x?: number, y?: number) {
        if (x == null) {
            x = parent.width - 10;
        }
        if (y == null) {
            y = 20;
        }

        this.pos(x, y);
        parent.addChild(this);
    }

    setActive(b: boolean, recover: boolean = false) {

        this.visible = b;

        if (b) {
            this.getEff(true).resume();
            return;
        }

        let item = this.getEff(false);
        item && item.pause();
        recover && badgeItem.recover(this);
    }


    onDestroy(): void {
        this.$tween && this.$tween.destroy();
        this.$tween = null;
    }
}
